<template>
	<view class="padding-bt-100 mainPage">
		<view class="padding padding-bottom-xl">
			<view class="address padding bg-white radius-xl margin-bottom"
				@tap="$utils.$page.open('/pages/user/address/list?pageType=order')">
				<view class="info">
					<view class="username margin-bottom-xs">
						<text class="text-bold text-black">{{ address.name }}</text>
						<text class="padding-left">{{ address.mobile }}</text>
					</view>
					<view class="detail text-sm text-gray">
						{{ address.province }} {{ address.city }} {{ address.area }} {{ address.street }} {{
							address.address_detail }}
					</view>
				</view>
				<view class="more">
					<text class="cuIcon-right text-bold"></text>
				</view>
			</view>

			<view class="padding bg-white radius-xl margin-bottom">
				<view class="project-list padding-bottom-xs">
					<view class="item radius-lg padding-tb" :class="projects.length - 1 != index ? 'solid-bottom' : ''"
						v-for="(item, index) in projects" :key="item.id">
						<image :src="item.thumb" mode="aspectFill" class="img"></image>
						<view class="probox">
							<view class="title text-bold text-black margin-bottom-xs">
								<text>{{ item.title }}</text>
								<view class="text-sm text-right cost text-red">
									<text class="text-bold">¥</text>
									<text class="text-lg text-bold">{{ item.price }}</text>
								</view>
							</view>
							<view class="text-gray margin-bottom-sm text-sm">{{ item.tips }}</view>
							<view class="price flex flex-wrap align-end">
								<view class="time flex-sub text-sm">
									<text class="cuIcon-timefill text-lg themeColor"></text>
									<text class="padding-left-mn">{{ item.service_duration }}分钟</text>
									<view class="flex align-center text-xs">
										<view>加钟：</view>
										<view class="flex-sub" v-if="item.overtime_state">
											<view v-if="item.overtime_separate">
												{{ item.overtime_price }}元/{{ item.overtime_duration }}分钟</view>
											<view v-else>跟随项目定价</view>
										</view>
										<view class="flex-sub" v-else>不可用</view>
									</view>
								</view>
								<view class="text-right liji flex align-end flex-direction">
									<u-number-box button-size="20" v-model="item.num" @change="valChange" :min="0"
										:max="item.overtime_state ? 99 : 1" :name="index">
									</u-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="serviceTechnician grid col-2 margin-bottom">
					<view class="">服务技师</view>
					<view class="text-right crow">
						<view class="cu-avatar sm round margin-left"
							:style="{ backgroundImage: 'url(' + technicianInfo.headimg + ')' }"></view>
						<text class="padding-lr-sm">{{ technicianInfo.nickname }}</text>
					</view>
				</view>

				<view class="serviceTime grid col-2">
					<view class="">服务时间</view>
					<view class="text-right" @click="toChangeServeTime()">
						<text class="padding-left-sm" :class="[form.scheduling_id ? 'themeColor' : 'text-grey text-sm']">{{
							servive_time }}</text>
						<text class="cuIcon-right"></text>
					</view>
				</view>
			</view>

			<!-- 出行方式 -->
			<view class="travel padding bg-white radius-xl margin-bottom">
				<view class="grid col-2">
					<view class="text-black text-bold">出行方式</view>
					<view class="text-right" @click="toChangeTravel()">
						<text class="text-orange">{{ form.travel.name }}</text>
						<text class="cuIcon-right"></text>
					</view>
				</view>
				<view class="tips padding-sm">{{ travel.text }}</view>
				<view class="fare">
					<label>车费</label>
					<view class="text-red margin-right-xs text-bold">￥{{ travel.price }}</view>
				</view>
			</view>

			<view class="coupon padding bg-white radius-lg margin-tb" @click="toSetCouponShow">
				<text>选择优惠券</text>
				<view class="selected">
					<text class="text-orange" v-if="coupon_price > 0">- ￥{{ coupon_price }}</text>
					<text class="cuIcon-right"></text>
				</view>
			</view>

			<view class="remark padding bg-white radius-xl margin-tb">
				<view>
					<textarea maxlength="255" placeholder="在此输入备注信息" v-model="form.remark"></textarea>
				</view>
			</view>
			<view class="bg-white radius-xl margin-tb">
				<view class="coupon padding">
					<text>基础服务合计,时长：{{ service_duration.basic_duration }}分钟</text>
					<view class="selected">
						<text class="text-red margin-right-xs text-bold">￥{{ price.basic_price }}</text>
					</view>
				</view>
				<view class="coupon padding">
					<text>加钟服务合计,时长：{{ service_duration.overtime_duration }}分钟</text>
					<view class="selected">
						<text class="text-red margin-right-xs text-bold">￥{{ price.overtime_price }}</text>
					</view>
				</view>
				<view class="coupon padding">
					<text>车费</text>
					<view class="selected">
						<text class="text-red margin-right-xs text-bold">￥{{ travel.price }}</text>
					</view>
				</view>
				<view class="coupon padding" v-if="coupon_price > 0">
					<text>优惠券</text>
					<view class="selected">
						<text class="text-red margin-right-xs text-bold">- ￥{{ coupon_price }}</text>
					</view>
				</view>
			</view>
			<view class="bg-white padding radius-xl margin-tb text-sm" v-if="travel.reach_time">
				<text>现在付款，技师约在</text>
				<text class="text-red margin-right-xs margin-left-xs text-bold">{{ travel.reach_time }}</text>
				<text>时间到达</text>
			</view>
			<x-refund-tips />
			<view class="text-sm text-gray">
				<text>请阅读</text>
				<text class="text-blue"
				@tap="$utils.$page.open('/pages/article/content?alias=reservation_pay')">《服务订购协议》</text>
				<text class="text-blue"
				@tap="$utils.$page.open('/pages/article/content?alias=pay')">《支付协议》</text>
			</view>
		</view>

		<view class="cu-bar bg-white tabbar shop foot flex">
			<view class="padding-left flex-sub">
				合计：<text class="text-red text-lg text-bold">¥{{ price_sum }}</text>
			</view>
			<view class="reservation text-right padding-right">
				<button class="cu-btn round china-btn-bg " @click="showPay">
					<text class="padding-lr-xl">立即下单</text>
				</button>
			</view>
		</view>

		<uPicker :show="travelShow" :columns="[travels]" keyName="name" @pickerPopup="pickerPopup" />

		<serviveTime :show="serviceTimeShow" :serviceDuration="service_duration_sum" :technicianId="form.technician_id"
			@serviceTimePopup="serviceTimePopup" />

		<payType :show="payTypeShow" :orders-type="form.type" @payCallBack="payCallBack" :price="price_sum" />

		<myCoupon :show="couponShow" :price="price.price" @couponPopup="couponPopup" />

		<loading v-if="pageLoading" />
	</view>
</template>

<script>
import serviveTime from './modules/serviceTime'; // 服务时间
export default {
	components: { serviveTime },
	data() {
		return {
			pageLoading: false,
			address: {
				name: '您还未设置默认地址',
				address_detail: '请选择地址',
			},
			projects: [],//项目信息
			technicianInfo: {},//技师信息
			servive_time: '选择服务时间',
			orders: {
				trade: ''
			},
			form: {
				pay_type: '',
				type: 'reservation',
				platform: '',
				technician_id: 0,
				address_id: 0,
				service: [],
				scheduling_id: 0,
				servive_time: '',
				remark: '',
				travel: {
					type: '',
					id: '',
					name: '',
					start_distance: 0,
					start_price: 0,
					mileage_price: 0,
					virtually_mileage: 0,
					commuting: 0
				},
				coupon: []
			},
			coupon: [],
			distance: 12000,
			travels: [],
			travelShow: false,//出行方式弹出层
			serviceTimeShow: false,//服务时间弹出层
			payTypeShow: false,//支付方式弹出层
			couponShow: false,//优惠券弹出层
		};
	},
	computed: {
		price() {
			let price = 0;
			let basic_price = 0;
			let overtime_price = 0;
			for (let i = 0; i < this.projects.length; i++) {
				const item = this.projects[i];
				let p = 0;
				let num = item.num;
				price += +item.price;
				basic_price += +item.price;
				num--;
				if (num > 0) {
					if (item.overtime_separate) {
						p = +item.overtime_price * num;
					} else {
						p = +item.price * num;
					}
				}
				overtime_price += p;
				price += p;
			}
			return { price: +price.toFixed(2), basic_price: +basic_price.toFixed(2), overtime_price: +overtime_price.toFixed(2) };
		},
		price_sum() {
			return +(this.price.price + this.travel.price - this.coupon_price).toFixed(2);
		},
		service_duration() {
			let service_duration = 0;
			let basic_duration = 0;
			let overtime_duration = 0;
			for (let i = 0; i < this.projects.length; i++) {
				const item = this.projects[i];
				let duration = 0;
				let num = item.num;
				service_duration += item.service_duration;
				basic_duration += item.service_duration;
				num--;
				if (num > 0) {
					if (item.overtime_separate) {
						duration = item.overtime_duration * num;
					} else {
						duration = item.service_duration * num;
					}
				}
				service_duration += duration;
				overtime_duration += duration;
			}
			return { service_duration, basic_duration, overtime_duration };
		},
		service_duration_sum() {
			return this.service_duration.service_duration + this.travel.commuting;
		},
		travel() {
			let result = { text: '请先选择地址和服务时间', price: 0, commuting: 0, reach_time: '' };
			const travel = this.form.travel;
			if (travel.type) {
				let start_distance = travel.start_distance * 1000;
				let distance = this.distance + this.distance * (travel.virtually_mileage / 100);
				let mileage = 0;
				let mileage_price = 0;
				let price = travel.start_price;
				if (start_distance > 0 && distance > start_distance) {
					mileage = distance - start_distance;
				}
				if (mileage > 0 && travel.mileage_price > 0) {
					mileage = Math.ceil(mileage / 1000);
					mileage_price = (mileage * travel.mileage_price).toFixed(2);
					price += +mileage_price;
				}
				result.text = `全程共${Math.ceil(distance / 1000)}，${travel.name}收取来回车费，单程起步${travel.start_price}元/${travel.start_distance}公里。`;
				if (mileage > 0) {
					result.text += `超出${mileage}公里,每公里收取${travel.mileage_price}元,共计${mileage_price}元。`;
				}
				result.price = price * 2;
				result.commuting = travel.commuting * Math.ceil(distance / 1000);
				result.text += `预计需要${result.commuting}分钟到达`;
				if (this.form.servive_time) {
					const today=new Date();
					const date = new Date(this.form.servive_time);
					date.setMinutes(date.getMinutes() + result.commuting);
					if (date.getDate() === today.getDate()) {
						result.reach_time = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
					} else {
						result.reach_time = `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
					}
				}
			}
			result.price=+result.price.toFixed(2);
			return result;
		},
		coupon_price() {
			let price = 0;
			for (let i = 0; i < this.coupon.length; i++) {
				const item = this.coupon[i];
				price += +item.money;
			}
			price = +price.toFixed(2);
			return price;
		}
	},
	onLoad(options) {
		this.pageLoading = true;
		this.form.platform = this.$utils.$system.platform();
		const ReservaData = this.$utils.useStorage().get('ReservaData');
		if (ReservaData) {
			this.projects = ReservaData.service;
			this.technicianInfo = ReservaData.technician;
			this.form.technician_id = ReservaData.technician.technician_id;
			this.getAddress();
		} else {
			this.pageLoading = false;
			uni.showModal({
				title: '提示',
				content: '请先选择预约项目',
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
						this.$utils.$page.back();
					}
				}
			});
		}
		uni.$on('SELECT_ADDRESS', (res) => {
			this.address = res;
			this.form.address_id = res.id;
			this.getDistance();
			this.getTravel();
		})
	},
	unLoad() {
		uni.$off('SELECT_ADDRESS');
	},
	methods: {
		getAddress() {
			this.$utils.$api.Address.getAddressDetails().then(data => {
				this.address = data;
				this.form.address_id = data.id;
				this.getDistance();
				this.getTravel();
			}).finally(() => {
				this.pageLoading = false;
			})
		},
		getDistance() {
			this.$utils.$api.Technician.getDistance({
				address_id: this.form.address_id,
				technician_id: this.form.technician_id
			}).then(data => {
				this.distance = data.distance;
			}).catch(err => {
				this.$utils.$message.error(err.msg);
			})
		},
		getTravel() {
			if (!this.address.city_id || !this.form.servive_time) return;
			this.$utils.$api.Travel.list({ city_id: this.address.city_id, servive_time: this.form.servive_time,technician_id:this.form.technician_id }).then(res => {
				this.travels = res.data;
				this.pickerPopup({
					type: 'confirm',
					data: res.data[0]
				});
			}).catch(err => {
				this.pickerPopup({
					type: 'confirm',
					data: {
						type: '',
						id: '',
						name: '',
						start_distance: 0,
						start_price: 0,
						mileage_price: 0,
						virtually_mileage: 0,
						commuting: 0
					}
				});
			})
		},
		showPay() {
			if (!this.form.address_id) {
				return uni.showModal({
					title: '提示',
					content: '还未选择地址，是否立即去选择？',
					confirmText: '去选择',
					success(res) {
						if (res.confirm) {
							this.$utils.$page.open('/pages/user/address/list?pageType=order');
						}
					}
				});
			}
			if (!this.form.scheduling_id) {
				return this.toChangeServeTime();
			}
			if (!this.form.travel.type) {
				return this.toChangeTravel();
			}
			this.payTypeShow = true;
		},
		payCallBack(pay_type) {
			if (pay_type) {
				this.form.pay_type = pay_type;
				this.form.service = this.projects.map(item => {
					return {
						id: item.id,
						num: item.num
					}
				});
				if (this.orders.trade) {
					this.getPayInfo();
				} else {
					this.getOrdersInfo();
				}
			}
			this.payTypeShow = false;
		},
		getPayInfo() {
			uni.showLoading({
				title: '获取订单中...',
				mask: true
			})
			this.$utils.$api.Orders.payByOrders({
				trade: this.orders.trade,
				platform: this.form.platform,
				pay_type: this.form.pay_type
			}).then((res) => {
				if (res.data.order && res.data.order.trade) {
					this.orders = res.data.order
				}
				this.pay(res);
			}).catch(err => {
				this.$utils.$message.error(err.msg);
				if (err.data && err.data.trade) {
					this.orders = err.data
				} else {
					this.orders = {
						trade: '',
					};
				}
			}).finally(() => {
				uni.hideLoading();
			})
		},
		getOrdersInfo() {
			uni.showLoading({
				title: '获取订单中...',
				mask: true
			})
			this.$utils.$api.Orders.create(this.form).then((res) => {
				if (res.data.order && res.data.order.trade) {
					this.orders = res.data.order
				}
				this.pay(res);
			}).catch(err => {
				this.$utils.$message.error(err.msg);
				if (err.data && err.data.trade) {
					this.orders = err.data
				}
			}).finally(() => {
				uni.hideLoading();
			})
		},
		pay(res) {
			if (res.code === this.$utils.$http.ResponseCode.SUCCESS) {
				setTimeout(() => {
					uni.showLoading({
						title: '查询中...',
						mask: true
					});
					this.$utils.usePay(res.data).then(() => {
						uni.$emit('UPDATE::ORDER');
						this.$utils.$api.User.userinfo(this, true);
						this.$utils.$page.redirect('/pages/order/payment/payment?trade=' + res.data.order.trade)
					}).catch(err => {
						if(err&&err.msg){
							this.$utils.$message.error(err.msg);
						}
					}).finally(() => {
						uni.hideLoading();
					});
				}, 300)
			} else if (res.code === this.$utils.$http.ResponseCode.PAY_SUCCESS) {
				uni.$emit('UPDATE::ORDER');
				this.$utils.$api.User.userinfo(this, true);
				this.$utils.$page.redirect('/pages/order/payment/payment?trade=' + res.data.order.trade)
			}
		},
		valChange(e) {
			let index = e.name;
			let num = e.value;
			const service = this.projects[index];
			if (num <= 0) {
				uni.showModal({
					title: '提示',
					content: `移除${service.title}服务？`,
					success: res => {
						if (res.confirm) {
							this.projects.splice(index, 1);
							this.$nextTick(() => {
								this.ReservaData();
							})
							if (this.projects.length <= 0) {
								this.$utils.useStorage().remove('ReservaData');
								this.$utils.$page.back();
							}
						} else if (res.cancel) {
							service.num = 1;
						}
					}
				})
			} else {
				this.$nextTick(() => {
					this.ReservaData();
				})
			}
		},
		ReservaData() {
			let ReservaData = {
				technician: this.technicianInfo,
				service: this.projects.filter(item => item.num > 0)
			};
			this.$utils.useStorage().set('ReservaData', ReservaData)
		},
		serviceTimePopup(e) {
			if (e.type == 'confirm') {
				const { data } = e;
				this.form.scheduling_id = data.id;
				this.servive_time = data.servive_time;
				this.form.servive_time = data.start_time;
				this.getTravel();
			}
			this.serviceTimeShow = false
		},
		pickerPopup(e) {
			if (e.type == 'confirm') {
				this.form.travel = e.data;
				this.cancelOrders();
			}
			this.travelShow = false;
		},
		couponPopup(data) {
			if (data && data.ids) {
				this.form.coupon = data.ids;
				this.coupon = data.coupon;
				this.cancelOrders();
			} else {
				this.form.coupon = [];
				this.coupon = [];
			}
			this.couponShow = false;
		},
		toChangeTravel() {
			if (this.travels.length <= 0) return;
			this.travelShow = true;
		},
		toChangeServeTime() {
			this.serviceTimeShow = true;
		},
		toSetCouponShow() {
			this.couponShow = true;
		},
		cancelOrders() {
			if (this.orders.trade) {
				this.$utils.$api.Orders.cancel(this.orders.trade).then(() => {
					this.orders = {
						trade: '',
					}
				}).catch(err => { })
			}
		}
	}
}
</script>

<style lang="less" scoped>
.address {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.project-list {
	.item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		height: 190upx;

		.img {
			width: 170upx;
			height: 140upx;
			border-radius: 10upx;
		}

		.probox {
			width: 70%;

			.title {
				display: flex;
				justify-content: space-between;
				align-items: baseline;

				.cost {
					width: 125upx;
				}
			}
		}
	}
}

.serviceTechnician {
	.crow {
		justify-content: flex-end;
	}
}

.goAddAddress {
	margin: auto;
}

.travel {
	.tips {
		background: #efefef;
		border-radius: 10rpx;
		margin-top: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
		color: blcak;
		line-height: 36rpx;
	}

	.fare {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
}

.remark {
	textarea {
		height: 100upx;
	}
}

.foot {
	height: 120upx;
}

.coupon {
	font-size: 14px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
